package com.core.framework.web.easyweb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.noe.framework.commons.config.Config;
import org.noe.framework.util.html.HtmlEscape;
 
public class RequestHelp {
	public static String getPathWithOutExt(HttpServletRequest request) {
		// Log.debug(request.getRequestURI());
		String path = request.getRequestURI();
		if (path.startsWith(request.getContextPath()))
			path = request.getRequestURI().substring(
					request.getContextPath().length());
		if (path.indexOf(".") > 0) {
			path = path.substring(0, path.lastIndexOf("."));
		}
		path = path.replaceAll("/{1}", "/");
		return path;
	}

	public static String getActionMethod(HttpServletRequest request) {
		String path = getPathWithOutExt(request);
		if (path.indexOf("!") > 0) {
			path = path.substring(path.lastIndexOf("!") + 1);
		} else {
			return "index";
		}
		return path;
	}

	public static String getActionPath(HttpServletRequest request) {
		String path = getPathWithOutExt(request);
		if (path.indexOf("!") > 0) {
			path = path.substring(0, path.lastIndexOf("!"));
		}
		if (path != null)
			path = path.replaceAll("/{2,}", "/");
		return path;
	}

	static public String sendRedirect(String url, HttpServletResponse response)
			throws Exception {
		RequestContext.getRequest().setAttribute("HttpServletResponseIsSend",
				"TRUE");
		response.sendRedirect(url);
		return null;
	}

	/**
	 * 页面跳转
	 * 
	 * @param url
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	static public String forward(String url, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.removeAttribute("javax.servlet.include.servlet_path");
		request.removeAttribute("javax.servlet.forward.servlet_path");
		request.setAttribute("javax.servlet.include.servlet_path", url);
		request.setAttribute("javax.servlet.forward.servlet_path", url);
		if (!response.isCommitted())
			request.getRequestDispatcher(url).forward(request, response);
		return "";
	}

	
	
	public static HttpServletRequest getEscapProxyRequest(HttpServletRequest req){
		InvocationHandler ih = new RequestInvocateHandler(req);
		if(req.getClass().toString().indexOf("Proxy")>-1){
			return req;
		}
		String noProxyWordConfig=Config.getString("SSys.req.noProxy");
		if(noProxyWordConfig==null||noProxyWordConfig.isEmpty()){
			noProxyWordConfig="";
			System.out.println("请配置SSys.req.noProxy 以保证request对象能够被合理的代理！！！");
		}
		String noProxyWords[]=noProxyWordConfig.split(",");
		for(String s:noProxyWords){
			if(!s.trim().isEmpty()){
				if(req.getRequestURI().contains(s)){
					return req;
				}
			}
		}
		HttpServletRequest reqproxy= (HttpServletRequest) Proxy.newProxyInstance(HttpServletRequest.class.getClassLoader(),
 				new Class[] { HttpServletRequest.class }, ih);
		return reqproxy;
	}
	public static void main(String args[]){
		HttpServletRequest req=(new HttpServletRequest(){

			@Override
			public String getAuthType() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getContextPath() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public Cookie[] getCookies() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public long getDateHeader(String name) {
				// TODO Auto-generated method stub
				return 0;
			}

			@Override
			public String getHeader(String name) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public Enumeration getHeaderNames() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public Enumeration getHeaders(String name) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public int getIntHeader(String name) {
				// TODO Auto-generated method stub
				return 0;
			}

			@Override
			public String getMethod() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getPathInfo() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getPathTranslated() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getQueryString() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getRemoteUser() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getRequestURI() {
				// TODO Auto-generated method stub
				return "a/abc/";
			}

			@Override
			public StringBuffer getRequestURL() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getRequestedSessionId() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getServletPath() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public HttpSession getSession() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public HttpSession getSession(boolean create) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public Principal getUserPrincipal() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public boolean isRequestedSessionIdFromCookie() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean isRequestedSessionIdFromURL() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean isRequestedSessionIdFromUrl() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean isRequestedSessionIdValid() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean isUserInRole(String role) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public Object getAttribute(String name) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public Enumeration getAttributeNames() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getCharacterEncoding() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public int getContentLength() {
				// TODO Auto-generated method stub
				return 0;
			}

			@Override
			public String getContentType() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public ServletInputStream getInputStream() throws IOException {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getLocalAddr() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getLocalName() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public int getLocalPort() {
				// TODO Auto-generated method stub
				return 0;
			}

			@Override
			public Locale getLocale() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public Enumeration getLocales() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getParameter(String name) {
				// TODO Auto-generated method stub
				return "<html></html>";
			}

			@Override
			public Map getParameterMap() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public Enumeration getParameterNames() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String[] getParameterValues(String name) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getProtocol() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public BufferedReader getReader() throws IOException {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getRealPath(String path) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getRemoteAddr() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getRemoteHost() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public int getRemotePort() {
				// TODO Auto-generated method stub
				return 0;
			}

			@Override
			public RequestDispatcher getRequestDispatcher(String path) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getScheme() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getServerName() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public int getServerPort() {
				// TODO Auto-generated method stub
				return 0;
			}

			@Override
			public boolean isSecure() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public void removeAttribute(String name) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void setAttribute(String name, Object o) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void setCharacterEncoding(String env)
					throws UnsupportedEncodingException {
				// TODO Auto-generated method stub
				
			}
			
		});
		System.out.println("xxx"+req+req.getClass());
		HttpServletRequest req2=RequestHelp.getEscapProxyRequest(req);
		System.out.println("xxx"+req2+req2.getParameter("xxx")+req2.getClass());
	     
	}
	
	
	/**
	 * 自定义 InvocationHandler 实现类,提供了传入 真正对象的 构造函数,
	 * 
	 * @author eric
	 * @date 2011-2-28 下午07:10:11
	 */
	public static class RequestInvocateHandler implements InvocationHandler {
		/**
		 * 该构造函数 可以设置 真正的 对象
		 * 
		 * @param data
		 *            真正要操作的对象
		 */
		public RequestInvocateHandler(HttpServletRequest data) {
			this.data = data;
		}

		// use this object to invoke method,not the one in arg list of invoke()
		private HttpServletRequest data;

		@Override
		public Object invoke(Object obj, Method method, Object[] args)
				throws Throwable {
			// before method invode
			// 这里使用 自己创建的对象调用方法,而不是 参数中的,参数中的对象只相当于1个代理,
			Object o = method.invoke(this.data, args);
			if (o != null && method.getName().equals("getParameter")) {
				String o1 = (String) o;
				if("jsonpage".equals(args[0])){
					//System.out.println("OK_@:"+args[0]+"@jsonpage@"+o1);
					return o;
				}
			//	if(!"_".equals(args[0]))
				//System.out.println("RequestInvocateHandler:"+args[0]+"@"+o1);
				
				return HtmlEscape.escape(o1);
			}
			if (o != null && method.getName().equals("getParameterMap")) {
				Map o1 = (Map) o;
//				if(!o1.containsKey("t"))
//				System.out.println("@"+o1);
				return HtmlEscape.escape(o1);
			}
		 
			return o;
		}
	}

}
